package algorithm;

public class leetcode_0904 {
    public int totalFruit(int[] fruits) {
        int len=fruits.length;
        if(len<=2) return len;
        int[][] collection=new int[2][2];
        collection[0][1]=1;
        collection[0][0]=fruits[0];
        collection[1][0]=-1;
        int num=1;
        int left=0;
        int max=1;
        for(int i=1;i<len;++i){
            if(fruits[i]==collection[0][0]||fruits[i]==collection[1][0]){
                if(fruits[i]==collection[0][0]){
                    collection[0][1]++;
                }
                else{
                    collection[1][1]++;
                }
            }
            else if(num<2){
                num+=1;
                collection[num-1][1]++;
                collection[num-1][0]=fruits[i];
            }
            else{
                max=(max>(collection[0][1]+collection[1][1])?max:(collection[0][1]+collection[1][1]));
                while(collection[0][1]!=0&&collection[1][1]!=0){
                    if(fruits[left]==collection[0][0]){
                        collection[0][1]--;
                        left++;
                    }
                    else{
                        collection[1][1]--;
                        left++;
                    }
                }
                if(collection[1][1]!=0){
                    collection[0][0]=collection[1][0];
                    collection[0][1]=collection[1][1];
                    collection[1][0]=fruits[i];
                    collection[1][1]=1;
                }
                else{
                    collection[1][0]=fruits[i];
                    collection[1][1]=1;
                }

            }
        }
        max=(max>(collection[0][1]+collection[1][1])?max:(collection[0][1]+collection[1][1]));
        return max;
    }
}
